package com.fzy.core.acegi;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.ui.AccessDeniedHandlerImpl;

public class MyAccessDeniedHandlerImpl extends AccessDeniedHandlerImpl {

	private String outsideError;
	private String insideError;

	public void handle(ServletRequest request, ServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException,
			ServletException {
		
		String targetUrl=((HttpServletRequest)request).getRequestURI()!=null?((HttpServletRequest)request).getRequestURI():"";
		String forwardUrl=targetUrl.indexOf("/site/")>-1?this.getOutsideError():this.getInsideError();
		
		String contextPath=((HttpServletRequest)request).getContextPath();
		if (forwardUrl != null) {
			// Put exception into request scope (perhaps of use to a view)
			((HttpServletRequest) request).setAttribute(
					ACEGI_SECURITY_ACCESS_DENIED_EXCEPTION_KEY,
					accessDeniedException);

			// Perform RequestDispatcher "forward"
			//RequestDispatcher rd = request.getRequestDispatcher(forwardUrl);
			((HttpServletResponse) response).sendRedirect(contextPath+"/"+forwardUrl);
		}
		if (!response.isCommitted()) {
			// Send 403 (we do this after response has been written)
			((HttpServletResponse) response).sendError(
					HttpServletResponse.SC_FORBIDDEN,
					accessDeniedException.getMessage());
		}
	}

	public String getOutsideError() {
		return outsideError;
	}

	public void setOutsideError(String outsideError) {
		this.outsideError = outsideError;
	}

	public String getInsideError() {
		return insideError;
	}

	public void setInsideError(String insideError) {
		this.insideError = insideError;
	}

}
